<?php

namespace App\Console\Commands;

use App\AdvertiserImg;
use App\Jobs\CheckImage;
use App\Service\DunImageService;
use Illuminate\Console\Command;

class ScheduleImage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'schedule:image';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时检查图片';

    protected $checkData = [];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $imageService = DunImageService::getInstance();
        $imageService->setConfig(
            \config('app.dun_image_secret_id'),
            \config('app.dun_image_secret_key'),
            \config('app.dun_image_business_id')
        );

        AdvertiserImg::query()->where('status', '=',0)->chunkById(20, function ($dataList) use ($imageService) {
            $dataList = $dataList->filter(function ($value) {
                return $value['status'] == 0;
            })->groupBy('account_id')->toArray();
            foreach ($dataList as $account => $list) {
                $checkData = [];
                foreach ($list as $item) {
                    if (empty($item['preview_url'])){
                        continue;
                    }
                    $checkData[] = [
                        "account" => $item['account_id'],
                        "name" => $item['image_id'],
                        "type" => 1,
                        "data" => $item['preview_url'],
                        'dataId' => $item['image_id'],
                        'callbackUrl' => config('app.url') . '/api/yd/image/callback'
                    ];
                }
                $imageService->main($checkData, $account);
                usleep(1000);
            }
//            CheckImage::dispatch($checkData);
        });
        return 0;
    }

    /**
     * @param array $data
     * @return void
     */
    private function addCheckData(array $data)
    {
        $this->checkData[] = $data;
        if (count($this->checkData) >= 20){
            $this->pushCheckData();
        }
    }

    /**
     * @return void
     */
    private function resetCheckData()
    {
        $this->checkData= [];
    }

    /**
     * @return void
     */
    private function pushCheckData()
    {
        CheckImage::dispatch($this->checkData);
        $this->resetCheckData();
    }
}
